package cn.chanel.mall.controller;

import cn.chanel.mall.constant.CookieName;
import cn.chanel.mall.entity.User;
import cn.chanel.mall.service.CartService;
import cn.chanel.mall.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/cart")
public class CartController {
    @Resource
    private UserService userService;

    @Resource
    private CartService cartService;

    @GetMapping("list")
    public ModelAndView listCart(@CookieValue(name = CookieName.USER_LOGIN, required = false) String user,
                                 Map<String, Object> map){
        if(StringUtils.hasText(user)){
            map.put("userInfo", userService.findUserById(user));
            map.put("cartVO", cartService.getUserCart(user));
            return new ModelAndView("cart", map);
        }else {
            // 未登录就去登录
            return new ModelAndView("redirect:/user/login?failed=false");
        }
    }

    @GetMapping("add")
    public ModelAndView addCart(@RequestParam String goods,
                                @RequestParam int num,
                                @CookieValue(name = CookieName.USER_LOGIN, required = false) String user
    ){
        if(StringUtils.hasText(user) && userService.findUserById(user) != null){
            cartService.addCart(user, goods, num);
            return new ModelAndView("redirect:/cart/list");
        }else {
            // 未登录就去登录
            return new ModelAndView("redirect:/user/login?failed=false");
        }
    }

    @GetMapping("delete")
    public ModelAndView deleteCart(@RequestParam String goods,
                                   @CookieValue(name = CookieName.USER_LOGIN, required = false) String user){
        if(StringUtils.hasText(user)){
            cartService.deleteUserCart(goods);
            return new ModelAndView("redirect:/cart/list");
        }else {
            // 未登录就去登录
            return new ModelAndView("redirect:/user/login?failed=false");
        }
    }
}
